package cn.edu.lingnan.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/admin/*")
public class AuthorityFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //当管理员登录时访问时，可以访问你想访问的页面；普通用户登录时，有些页面没权限
        //当管理员登陆时，你可以访问/admin/admin.jsp;当普通用户登陆时，返回/authority.html

        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        HttpSession session=req.getSession();
        Integer right=(Integer)session.getAttribute("right");
        System.out.println("[Debug]the student's right is " + right);
        //right值的可能：0、1、null
        if (right!=null){//登录成功
            if (right==1){//管理员登录
                chain.doFilter(request,response);
            }else {//学生登录
                resp.sendRedirect(req.getContextPath()+"/authority.html");
            }

        }else {//没登录
            resp.sendRedirect(req.getContextPath()+"/index.html");
        }
    }

    @Override
    public void destroy() {

    }
}
